<?php

namespace app\controller\warehouse;

use app\Auth;
use app\BaseController;
use lc\helpers\Helper;
use app\Request;
use lc\helpers\Response;
use think\captcha\facade\Captcha;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{

    /**
     * 跳转首页
     * @return string
     */
    public function index()
    {

        View::config(['view_path' => dirname($this->app->getRootPath()) . '/']);
        return View::fetch('/index');

    }

    /**
     * 验证码
     */
    public function Captcha()
    {
        return Captcha::create();
    }

    /**
     * 登录
     */

    public function login(Request $request)
    {

        if (captcha::check($request['captcha'])) {
            // 验证失败
            return Response::fail('验证失败');
        }

        //校验账号密码
        $adminData = Db::name('admin')->field('id,account,password,salt,role')->where('account', $request['account'])->find();

        if (empty($adminData)) return Response::fail('未找到账号,请重新输入');

        if (md5($request['password'] . $adminData['salt']) === $adminData['password']) {

            Db::name('admin')->where('id',$adminData['id'])->update([
                'login'=>time(),
                'token'=>Helper::generateNonceStr(),
                'expired'=>time()+7200
            ]);

            //登录成功
            return Response::success(
                [
                    'id' => $adminData['id'],
                    'warehouseName'=>$adminData['warehouse_name'],
                    'warehousePerson'=>$adminData['warehouse_person'],
                    'role'=>$adminData['role']
                ]
            );
        } else {
            return response::fail('密码错误,请重新输入');
        }
    }


    /**
     * 修改密码
     * @return void
     */
    public function updatePassword(Request $request){

        $adminId = Auth::$adminId;
        $admin = Auth::$admin;

        //查找盐值

        $update = Db::name('admin')->where('id',$adminId)->update([
            'password'=>md5($request['password'].$admin->salt),
            'expired'=>time()
        ]);

        //
        if($update != 0){
            return Response::success();
        }else{
            return Response::fail('修改失败');
        }
    }


    /**
     * 退出登录
     * @return void
     */
    public function quitLogin(){

        $adminId = Auth::$adminId;
        Db::name('admin')->where('id',$adminId)->update([
            'expired'=>time()
        ]);

        return Response::success();
    }




}
